package com.bootdo.app.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.system.domain.FileDO;
import com.bootdo.system.domain.FileShareDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserFileDO;
import com.bootdo.system.service.FileShareService;
import com.bootdo.system.service.UserFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/app/userFile/")
public class AppUserFileController {

    // 存放路径导航的文件集合
    private List<UserFileDO> folios = null;

    @Autowired
    private UserFileService userFileService;

    @Autowired
    private FileShareService fileShareService;

    @Autowired
    private CacheManager cacheManager;

    /***
     * 获取文件列表信息
     * @param params
     * @return
     */
    @PostMapping("/listFile")
    @ResponseBody
    public R listFile(@RequestParam Map<String, Object> params, UserFileDO userFileDO,HttpServletRequest request) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        //查询列表数据
        params.put("userid",userDO.getUserId().toString());
        if(null != userFileDO.getBelong()) {
            params.put("belong",userFileDO.getBelong());
        }else {
            params.put("belong",-1);
        }
        params.put("isreceive","0");
        Query query = new Query(params);
        List<UserFileDO> userFileDOList = userFileService.listFile(query);
        int count = userFileService.countFile(params);
        PageUtils pageUtils = new PageUtils(userFileDOList,getFolios(userFileDO.getUserid(), userFileDO.getBelong()),count);
        return R.ok(pageUtils);
    }

    private List<UserFileDO> getFolios(Long userid, Integer belong) {
        folios = new ArrayList<UserFileDO>();
        getFolio(belong);
        return folios;
    }

    private void getFolio(int belong) {
        UserFileDO userFileDO = userFileService.getDetail(belong);
        if (userFileDO == null) {
            return;
        }
        if (userFileDO.getBelong() > 0) {
            getFolio(userFileDO.getBelong());
        }
        folios.add(userFileDO);
    }

    /***
     * 创建文件夹
     * @param userFileDO
     * @return
     */
    @PostMapping("/establishFile")
    @Log("创建文件夹")
    @ResponseBody
    public R establishFile(UserFileDO userFileDO,HttpServletRequest request) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        R r = new R();
        //创建人
        userFileDO.setUserid(userDO.getUserId());
        userFileDO.setUsername(userDO.getUsername());
        r = userFileService.createDir(userFileDO);
        return r;
    }

    /**
     * 文件上传
     * @param fileDO
     * @param theFile
     * @param userFileDO
     * @return
     */
    @PostMapping("/uploadFileFor")
    @Log("文件上传")
    @ResponseBody
    public R uploadFileFor(FileDO fileDO, MultipartFile[] theFile, UserFileDO userFileDO,HttpServletRequest request) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        R r = new R();
        //创建人
        userFileDO.setUserid(userDO.getUserId());
        userFileDO.setUsername(userDO.getUsername());
        try {
            r = userFileService.uploadFileFor(fileDO,theFile,userFileDO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 文件取消上传
     * @param fileDO
     * @return
     */
    @PostMapping("/cancelUploadFile")
    @Log("文件取消上传")
    @ResponseBody
    public R cancelUploadFile(FileDO fileDO,HttpServletRequest request) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        R r = userFileService.cancelUploadFile(fileDO);
        return r;
    }

    /**
     * 文件同步到另一台服务器
     * @param rootPath
     * @param actualPath
     * @param file
     * @return
     */
    @PostMapping("/synchroFile")
    @ResponseBody
    public R uploadFile(String rootPath, String actualPath, MultipartFile file,String fileId,String uuid,String fileName,String fileType) {
        R r = new R();
        r = userFileService.synchroFile(rootPath,actualPath,file,fileId,uuid,fileName,fileType);
        return r;
    }

    /**
     * 判断文件是否可以下载
     * @param fileShareDO
     * @return
     */
    @PostMapping("/judeDownloadFile")
    @ResponseBody
    public R judeDownloadFile(FileShareDO fileShareDO,HttpServletRequest request) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        R r = new R();
        r = fileShareService.judeDownloadFile(fileShareDO);
        return r;
    }

    /**
     * 文件下载
     * @param fileShareDO
     * @return
     */
    @GetMapping("/downloadFile")
    @Log("文件下载")
    public R downloadFile(FileShareDO fileShareDO, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        fileShareService.downloadFile(fileShareDO,request,response);
        return R.ok();
    }

    /**
     * 判断文件是否可以发送
     */
    @PostMapping("/judeSend")
    @ResponseBody
    public R judeSend(@RequestParam("ids[]") Integer[] ids,HttpServletRequest request){
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        R r = new R();
        r = userFileService.judeSend(ids);
        return r;
    }

    /**
     * 删除文件及文件夹
     */
    @PostMapping("/deleteFile")
    @Log("文件删除")
    @ResponseBody
    public R deleteFile(@RequestParam("ids[]") Integer[] ids,HttpServletRequest request){
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        R r = new R();
        r = userFileService.deleteFile(ids);
        return r;
    }

    /**
     * 判断文件是否可以删除（文件夹下有文件不可删除）
     */
    @PostMapping("/judeDeleteFile")
    @ResponseBody
    public R judeDeleteFile(@RequestParam("ids[]") Integer[] ids,HttpServletRequest request){
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        Cache cache = cacheManager.getCache("user");
        UserDO userDO = cache.get(token, UserDO.class);
        if(null == userDO) {
            return R.error("当前用户信息已失效，请重新登录");
        }
        R r = new R();
        r = userFileService.judeDeleteFile(ids);
        return r;
    }

}
